package com.hiyee.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hiyee.pojo.auth.CustomerTokenInfo;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT token 工具类
 *
 * @author WangBin
 */
public class JWTUtil {

    // 有效的毫秒数 10 小时
    public static final long JWT_EXPIRED_TIME = 10 * 60 * 60 * 1000;
    // 密钥
    private static final String JWT_SECRET = "!@#88888@#!$%..";

    /**
     * 生成 token
     *
     * @param Map<String, Object> data
     * @return String
     */
    public static String create(Map<String, Object> data) {
        String token = "";
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
            Map<String, Object> header = new HashMap<>();
            header.put("author", "veer6");
            header.put("company", "hiyee.shop");
            token = JWT.create()
                    .withHeader(header)
                    .withIssuer("hiyee.shop")
                    .withIssuedAt(new Date())
                    .withSubject("jwt token")
                    .withAudience("202211021100")
                    .withExpiresAt(new Date(System.currentTimeMillis() + JWT_EXPIRED_TIME))
                    .withClaim("customerId", Long.parseLong(data.get("customerId").toString()))
                    .withClaim("nickname", data.get("nickname").toString())
                    .sign(algorithm);
        } catch (JWTCreationException exception) {
            exception.printStackTrace();
        }
        return token;
    }

    /**
     * 解析 token
     *
     * @param String token
     * @return CustomerTokenInfo
     */
    public static CustomerTokenInfo verify(String token) {
        CustomerTokenInfo customerTokenInfo = new CustomerTokenInfo();
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            customerTokenInfo.setCustomerId(jwt.getClaim("customerId").asLong());
            customerTokenInfo.setNickname(jwt.getClaim("nickname").asString());
        } catch (JWTVerificationException exception) {
            exception.printStackTrace();
        }
        System.out.println("token 解析：" + customerTokenInfo.getCustomerId());
        return customerTokenInfo;
    }

    /**
     * 获取请求头的 token
     *
     * @param HttpServletRequest request
     * @return String
     */
    public static String getHeaderToken(HttpServletRequest request)
    {
        try {
            return request.getHeader("Authorization").replace("Bearer ", "");
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return null;
    }
}
